package top.vains.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.vains.dto.RolePermissionDto;
import top.vains.entity.RolePermission;
import top.vains.exception.CustomerException;
import top.vains.mapper.RolePermissionMapper;
import top.vains.service.IRolePermissionService;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author vains
 * @since 2020-02-17
 */
@Slf4j
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Override
    public List<Integer> getRolePermissionId(Integer roleId) {
        return baseMapper.getRolePermissionId(roleId);
    }

    @Override
    public void updateRolePermissions(RolePermissionDto rolePermissionDto) {
        if (rolePermissionDto == null) {
            throw new CustomerException("角色和权限的信息不能为空");
        }
        List<Integer> permissionId = rolePermissionDto.getPermissionId();
        log.info("先删除角色对应的所有权限，角色ID：", rolePermissionDto.getRoleId());
        UpdateWrapper<RolePermission> wrapper = new UpdateWrapper<>();
        wrapper.eq("role_id", rolePermissionDto.getRoleId());
        baseMapper.delete(wrapper);
        if (CollectionUtils.isEmpty(permissionId)) {
            log.info("如果权限信息是空的，则不添加新的权限信息");
            return;
        }
        log.info("将新的权限信息添加进去");
        permissionId.forEach(e -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPid(e);
            rolePermission.setRoleId(rolePermissionDto.getRoleId());
            baseMapper.insert(rolePermission);
        });
    }
}
